package com.mycompany.controller.account;

import javax.annotation.Resource;

import org.broadleafcommerce.profile.core.domain.Customer;
import org.broadleafcommerce.profile.core.service.CustomerService;
import org.springframework.social.connect.Connection;
import org.springframework.social.facebook.api.Facebook;

public class FacebookSaveDataService {
	@Resource(name="blCustomerService")
	private CustomerService customerService;

	@SuppressWarnings("null")
	public String saveOrUpdate(Connection<?> connection) 
	{
		Customer customerInDb = customerService.readCustomerByEmail(connection.fetchUserProfile().getEmail());
System.out.println(customerInDb);
		if(customerInDb != null)
		{

			customerInDb.setUsername(connection.fetchUserProfile().getEmail());
			customerInDb.setFirstName(connection.fetchUserProfile().getFirstName());
			customerInDb.setLastName(connection.fetchUserProfile().getLastName());


			// get more data from facebook
			Facebook facebook = (Facebook) connection.getApi();

			customerService.saveCustomer(customerInDb);

			return connection.fetchUserProfile().getEmail();
		}

		else
		{

			Customer customer = null;
			customer.setEmailAddress(connection.fetchUserProfile().getEmail());
			customer.setUsername(connection.fetchUserProfile().getEmail());
			customer.setFirstName(connection.fetchUserProfile().getFirstName());
			customer.setLastName(connection.fetchUserProfile().getLastName());
			customer.setId(customerService.findNextCustomerId());
			customer.setPassword(Double.toString(Math.random()));
			// get more data from facebook
			Facebook facebook = (Facebook) connection.getApi();

			customerService.registerCustomer(customer, customer.getPassword(), customer.getPassword());

			return customer.getEmailAddress();
		}
	}



}
